package com.ht.module.bus.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ht.config.dataAuth.DataScope;
import com.ht.constant.BusConstant;
import com.ht.constant.DicConstants;
import com.ht.module.bus.entity.TClass;
import com.ht.module.bus.mapper.TClassMapper;
import com.ht.module.bus.service.TClassService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ht.module.bus.service.TDistrictService;
import com.ht.module.sys.entity.SysDictItem;
import com.ht.module.sys.service.ISysDictService;
import com.ht.module.sys.service.impl.SysDictServiceImpl;
import com.ht.util.CommMethod;
import com.ht.util.Pager;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Year;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hejialun
 * @since 2024-07-29
 */
@Service
public class TClassServiceImpl extends ServiceImpl<TClassMapper, TClass> implements TClassService {
    @Resource
    private ISysDictService sysDictService;
    @Resource
    private TDistrictService districtService;

    @Override
    public Pager<TClass> findPageAuth(Pager<TClass> pager, TClass en) {
        QueryWrapper<TClass> qw = getQW(en);
        baseMapper.findPageAuth(pager, qw, new DataScope().initOrder(pager));
        //设置年级
        setGrade(pager.getRecords());
        return pager;
    }

    @Override
    public List<TClass> findListAuth(TClass en) {
        QueryWrapper<TClass> qw = getQW(en);
        List<TClass> list = baseMapper.findList(qw, new DataScope());
        //设置年级
        setGrade(list);
        return list;
    }

    @Override
    public Pager<TClass> findPage(Pager<TClass> pager, TClass en) {
        QueryWrapper<TClass> qw = getQW(en);
        baseMapper.findPageAuth(pager, qw, null);
        //设置年级
        setGrade(pager.getRecords());
        return pager;
    }

    @Override
    public List<TClass> findList(TClass en) {
        QueryWrapper<TClass> qw = getQW(en);
        List<TClass> list = baseMapper.findList(qw, null);
        //设置年级
        setGrade(list);
        return list;
    }

    /**
     * 设置年级
     *
     * @param classes
     */
    @Override
    public void setGrade(List<TClass> classes) {
        //查询字典
        List<SysDictItem> educationStage = sysDictService.getItem("education_stage");
        this.setGrade(classes, educationStage);
    }

    @Override
    public void setGrade(List<TClass> classes, List<SysDictItem> educationStage) {
        // 获取当前年份
        int currentYear = Year.now().getValue();

        for (TClass aclass : classes) {
            int yearsPassed = currentYear - aclass.getSchoolGrade() + 1;
            switch (aclass.getEducationStage()) {
                case DicConstants.EducationStage.YEY:
                    if (yearsPassed > DicConstants.EducationStage.YEY_YEARS) {
                        yearsPassed = -1;
                    }
                    break;
                case DicConstants.EducationStage.XX:
                    if (yearsPassed > DicConstants.EducationStage.XX_YEARS) {
                        yearsPassed = -1;
                    }
                    break;
                case DicConstants.EducationStage.CZ:
                    if (yearsPassed > DicConstants.EducationStage.CZ_YEARS) {
                        yearsPassed = -1;
                    }
                    break;
                case DicConstants.EducationStage.GZ:
                    if (yearsPassed > DicConstants.EducationStage.GZ_YEARS) {
                        yearsPassed = -1;
                    }
                    break;
                default:
                    // 教育阶段不正确
                    yearsPassed = -2;
            }


            if (yearsPassed == -1) {
                aclass.setGrade("已毕业");
            } else if (yearsPassed == -2) {
                aclass.setGrade("教育阶段不正确");
            } else {
                SysDictItem item = educationStage.stream().filter(x -> StrUtil.equals(x.getValue(), aclass.getEducationStage())).findFirst().orElse(null);
                if (item != null) {
                    //获取当前年级的文本
                    String strYear = CommMethod.convertNumberToChinese(yearsPassed);
                    String text = DicConstants.EducationStage.textMap.get(item.getValue());
                    if(BeanUtil.isNotEmpty(text)){
                        aclass.setGrade(
                                text.replace("${}", strYear)
                        );
                    }
                }
            }
        }
    }


    @Override
    public void add(TClass en) {
        baseMapper.insert(en);
    }

    @Override
    public void editById(TClass en) {
        baseMapper.updateById(en);
    }

    private QueryWrapper<TClass> getQW(TClass en) {
        QueryWrapper<TClass> qw = new QueryWrapper<>();
        if (StrUtil.isNotEmpty(en.getClassName())) {
            qw.like("tab.class_name", en.getClassName());
        }
        if (StrUtil.isNotEmpty(en.getClassCode())) {
            qw.eq("tab.class_code", en.getClassCode());
        }

        if (StrUtil.isNotEmpty(en.getSchoolName())) {
            qw.like("tab.school_name", en.getSchoolName());
        }
        if (StrUtil.isNotEmpty(en.getSchoolCode())) {
            qw.eq("tab.school_code", en.getSchoolCode());
        }
        if (StrUtil.isNotEmpty(en.getClassBoardingArrangement())) {
            qw.eq("tab.class_boarding_arrangement", en.getClassBoardingArrangement());
        }

        if (StrUtil.isNotEmpty(en.getGradeCode())) {
            //分隔年级
            String[] split = en.getGradeCode().split(",");
            if (split.length > 1) {
                //分隔成字符串
                qw.eq("school_code", split[0]);
                //获取字符串中的一二三四
                Pattern pattern = Pattern.compile("[零一二三四五六七八九]");
                Matcher matcher = pattern.matcher(split[1]);

                // 用于保存提取出的中文数字
                StringBuilder extractedDigits = new StringBuilder();
                // 提取匹配的中文数字
                while (matcher.find()) {
                    extractedDigits.append(matcher.group());
                }
                //获取层级年级
                if(en.getGradeCode().contains("幼")){
                    qw.eq("education_stage",DicConstants.EducationStage.YEY);
                }

                if(en.getGradeCode().contains("年级")){
                    qw.eq("education_stage",DicConstants.EducationStage.XX);
                }


                if(en.getGradeCode().contains("初")){
                    qw.eq("education_stage",DicConstants.EducationStage.CZ);
                }

                if(en.getGradeCode().contains("高")){
                    qw.eq("education_stage",DicConstants.EducationStage.GZ);
                }

                //获取年级数字
                qw.eq("grade_number",CommMethod.convertChineseToArabic(extractedDigits.toString()));



            }
        }

        if (StrUtil.isNotEmpty(en.getState())) {
            qw.eq("tab.state", en.getState());
        }

        if (StrUtil.isNotEmpty(en.getDistrictCode())) {
            List<String> sonList = districtService.getSonList(en.getDistrictCode());
            sonList.add(en.getDistrictCode());
            qw.in("tab.district_code", sonList);
        }

        qw.eq("tab.del_flag", BusConstant.DEL_FLAG_N);
        qw.orderByDesc("tab.create_date");
        return qw;
    }
}
